package net.csdn.business.gateway.handler;

import org.springframework.cloud.gateway.config.GlobalCorsProperties;
import org.springframework.cloud.gateway.handler.FilteringWebHandler;
import org.springframework.cloud.gateway.handler.RoutePredicateHandlerMapping;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.core.env.Environment;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author likun
 * @date 2023/5/5 16:25
 */
public class CustomRoutePredicateHandlerMapping extends RoutePredicateHandlerMapping {
    public CustomRoutePredicateHandlerMapping(FilteringWebHandler webHandler, RouteLocator routeLocator, GlobalCorsProperties globalCorsProperties, Environment environment) {
        super(webHandler, routeLocator, globalCorsProperties, environment);
    }

    /**
     * 补充router信息
     * 参考 {@link org.springframework.boot.actuate.metrics.web.reactive.server.WebFluxTags} 解决采集 http_server_requests_seconds 相关指标 uri="UNKNOWN" 问题
     *
     * @param exchange ex
     * @return Route
     */
    @Override
    protected Mono<Route> lookupRoute(ServerWebExchange exchange) {
        Mono<Route> route = super.lookupRoute(exchange);
        try {
            exchange.getAttributes().put(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, route.block().getMetadata().get("pattern"));
        } catch (Exception ignore) {

        }
        return route;
    }
}